package config

import (
	"log"

	"github.com/spf13/viper"
)

type Config struct {
	Consul ConsulConfig `mapstructure:"consul"`
}

type ConsulConfig struct {
	Host   string `mapstructure:"host"`
	Port   int    `mapstructure:"port"`
	Scheme string `mapstructure:"scheme"`
}

var AppConfig *Config

func LoadConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	AppConfig = &Config{}
	err = viper.Unmarshal(AppConfig)
	if err != nil {
		log.Fatalf("Unable to decode into struct: %v", err)
	}
}

func SaveConfig() error {
	viper.Set("consul.host", AppConfig.Consul.Host)
	viper.Set("consul.port", AppConfig.Consul.Port)
	viper.Set("consul.scheme", AppConfig.Consul.Scheme)
	return viper.WriteConfig()
}
